//
//  GuideViewController.m
//  liwushuo
//
//  Created by qf1 on 16/4/15.
//  Copyright (c) 2016年 ZJH. All rights reserved.
//

#import "GuideViewController.h"
#import "AdvDetailViewController.h"
#import "DetailViewController.h"
#import "GuideTopicViewController.h"

@interface GuideViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (assign,nonatomic)NSInteger offset;
@property (assign,nonatomic)NSInteger JXoffset;


@end

@implementation GuideViewController

- (void)viewDidLoad {
    _offset = 0;
    [super viewDidLoad];
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.detailsLabelText = @"请稍后";
    [hud show:YES];
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = YES;
    self.title = @"指南";
    _contentArray = [[NSMutableArray alloc] init];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createView];
    [self getData];

}

- (void)awakeFromNib {
    [self setTabBarImage];
}

- (void)setTabBarImage{
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage * image = [UIImage imageNamed:@"guide2"];
    
    [self.tabBarItem setSelectedImage:image];
    
}

- (void)createView{
    [self createNavigationView];
    [self createContentView];
}

- (void)createNavigationView{
    _topScroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, 25)];
    _topScroller.userInteractionEnabled = YES;
    _topScroller.bounces = NO;
    _topScroller.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_topScroller];
    [_topScroller addSubview:({
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn setTitle:@"精选" forState:UIControlStateNormal];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.frame = CGRectMake(0, 0, 60, 25);
        btn.tag = 200;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(0, 0, 60, 25);
        btn;
    })];
}

- (void)createContentView{
    _contentScroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 25, theScreenWidth, theScreenHeight - 25 - 49)];
    _contentScroller.showsHorizontalScrollIndicator = NO;
    _contentScroller.pagingEnabled = YES;
    _contentScroller.delegate = self;
    [self.view addSubview:_contentScroller];
    [_contentScroller addSubview:({
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, theScreenHeight - 25 - 49 - 64) style:UITableViewStyleGrouped];
        _tableView.rowHeight = theScreenWidth * 2 / 5;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tag = 10086;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"GuideContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        [self createJXView];
        [_tableView addHeaderWithTarget:self action:@selector(headerAction)];
        [_tableView addFooterWithTarget:self action:@selector(footerAction)];
        _tableView.headerRefreshingText = @"正在刷新哟";
        _tableView.footerRefreshingText = @"正在加载哟";
        _tableView;
        
    })];
    
    
}

#pragma mark 创建精选页面
- (void)createJXView{
    UIView * headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, theScreenWidth * 2 / 5 + 80)];
    _advScroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, theScreenWidth * 2 / 5)];
    _advScroller.pagingEnabled = YES;
    _advScroller.delegate = self;
    _advScroller.showsHorizontalScrollIndicator = NO;
    [headView addSubview:_advScroller];
    _TopicScroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, theScreenWidth * 2 / 5, theScreenWidth, 80)];
    _TopicScroller.showsHorizontalScrollIndicator = NO;
    [headView addSubview:_TopicScroller];
    _tableView.tableHeaderView = headView;
    
}

#pragma mark 获取数据
- (void)getData{
    NetWorkManager * manager = [[NetWorkManager alloc] init];
    __weak GuideViewController * weakself = self;
    [manager getNavigationNameAndBlock:^(id respond) {
        _navigationArray = [[NSMutableArray alloc] initWithArray:respond];
        _topScroller.contentSize = CGSizeMake((_navigationArray.count + 1)* 55, 25);
        
        for (int i = 0; i < _navigationArray.count; i ++) {
            NavigationItem * item = _navigationArray[i];
            [_topScroller addSubview:({
                UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:12];
                [btn setTitle:item.name forState:UIControlStateNormal];
                btn.titleLabel.textAlignment = NSTextAlignmentCenter;
                btn.tag = 201 + i;
                [btn addTarget:weakself action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
                btn.frame = CGRectMake((i + 1) * 55, 0, 55, 25);
                btn;
            })];
        }
        
        _contentScroller.contentSize = CGSizeMake(theScreenWidth * (_navigationArray.count + 1), theScreenHeight - 89 - 49);
        
        for (int i = 0; i < _navigationArray.count; i ++) {
            //
            NetWorkManager * manager = [[NetWorkManager alloc] init];
            NavigationItem * item = _navigationArray[i];
            NSMutableString * urlStr = [[NSMutableString alloc] initWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?gender=1&limit=20&offset=0&generation=2",item.ID];
            [manager getContentDataWithUrl:urlStr andBlock:^(id respond) {
                [_contentArray addObject:respond];
                _count ++;
                if (_count == _navigationArray.count) {
                    [weakself sortArray:_contentArray];
                    for (int i = 0; i < _contentArray.count; i ++) {
                        UITableView * tableView = (UITableView *)[weakself.view viewWithTag:101 + i];
                        [tableView reloadData];
                    }
                    _count = 0;
                }
            }];
            //
            [_contentScroller addSubview:({
                UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake((i + 1) * theScreenWidth, 0, theScreenWidth, theScreenHeight - 64 - 49 - 25) style:UITableViewStylePlain];
                tableView.delegate = weakself;
                tableView.dataSource = weakself;
                tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
                tableView.rowHeight = theScreenWidth * 2 / 5;
                tableView.tag = 101 + i;
                [tableView registerNib:[UINib nibWithNibName:@"GuideContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
                [tableView addHeaderWithTarget:weakself action:@selector(headerAction)];
                [tableView addFooterWithTarget:weakself action:@selector(footerAction)];
                tableView.headerRefreshingText = @"正在刷新哟";
                tableView.footerRefreshingText = @"正在加载哟";
                tableView;
            })];
        }
        _redViewScroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0 , 23, 55 * (_navigationArray.count + 1), 2)];
        _redViewScroller.contentSize = CGSizeMake(110 * (_navigationArray.count + 1), 2);
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(_navigationArray.count * 55, 0, 55, 2)];
        view.backgroundColor = [UIColor redColor];
        [_redViewScroller addSubview:view];
        [_topScroller addSubview:_redViewScroller];
        [_redViewScroller setContentOffset:CGPointMake(55 * _navigationArray.count, 0)];
        
        [MBProgressHUD hideAllHUDsForView:weakself.view animated:YES];
        
    }];
    [manager getAdvDataAndBlock:^(id respond) {
        _advArray = [[NSMutableArray alloc] initWithArray:respond];
        NSMutableArray * imageArray = [[NSMutableArray alloc] initWithArray:respond];
        
        [imageArray insertObject:_advArray.lastObject atIndex:0];
        [imageArray addObject:_advArray.firstObject];
        _advScroller.contentSize = CGSizeMake(imageArray.count * theScreenWidth, theScreenWidth * 2 / 5);
        for (int i = 0; i < imageArray.count; i ++) {
            AdvItem * item = imageArray[i];
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * theScreenWidth, 0, theScreenWidth, theScreenWidth * 2 / 5)];
            imageView.userInteractionEnabled = YES;
            [imageView setImageWithURL:[NSURL URLWithString:item.image_url]];
            imageView.tag = 301 + i;
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:weakself action:@selector(tapAction:)];
            
            [_advScroller addSubview:imageView];
            [imageView addGestureRecognizer:tap];
        }
        [_advScroller setContentOffset:CGPointMake(theScreenWidth, 0)];
        [NSTimer scheduledTimerWithTimeInterval:3 target:weakself selector:@selector(scrollMove) userInfo:nil repeats:YES];
    }];
    [manager getTopicDataAndBlock:^(id respond) {
        _topicArray = [[NSMutableArray alloc] initWithArray:respond];
        _TopicScroller.contentSize = CGSizeMake(70 * _topicArray.count + 10, 80);
        for (int i = 0; i < _topicArray.count; i ++) {
            TopicItem * item = _topicArray[i];
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * 70 + 10, 10, 60, 60)];
            imageView.userInteractionEnabled = YES;
            [imageView setImageWithURL:[NSURL URLWithString:item.image_url]];
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:weakself action:@selector(changeAction:)];
            [imageView addGestureRecognizer:tap];
            imageView.tag = 401 + i;
            [_TopicScroller addSubview:imageView];
        }
    }];
    [manager getJXContentDataWithUrl:@"http://api.liwushuo.com/v2/channels/101/items?ad=2&gender=1&generation=2&limit=20&offset=0" andBlock:^(id respond) {
        _firstArray = [[NSMutableArray alloc] initWithArray:[weakself packDataWithArray:respond]];
        [_tableView reloadData];
    }];
    
}



#pragma mark 下拉刷新 上拉加载
- (void)headerAction{
    __weak GuideViewController * weakself = self;
    _offset = 0;
    _JXoffset = 0;
    NetWorkManager * manager = [[NetWorkManager alloc] init];
    int i = _contentScroller.contentOffset.x / theScreenWidth;
    if (i == 0) {
        [manager getJXContentDataWithUrl:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/101/items?ad=2&gender=1&generation=2&limit=20&offset=%ld",(long)_JXoffset] andBlock:^(id respond) {
            _firstArray = [[NSMutableArray alloc] initWithArray:[weakself packDataWithArray:respond]];
            [_tableView reloadData];
        }];
        
        [_tableView headerEndRefreshing];
    }else{
        NavigationItem * item = _navigationArray[i - 1];
        NSMutableString * urlStr = [[NSMutableString alloc] initWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?gender=1&limit=20&offset=%ld&generation=2",item.ID,(long)_offset];
        [manager getContentDataWithUrl:urlStr andBlock:^(id respond) {
            [_contentArray setObject:respond atIndexedSubscript:i - 1];
            UITableView * tableView = (UITableView *)[weakself.view viewWithTag:100 + i];
            [tableView reloadData];
            [tableView headerEndRefreshing];
        }];
    }
    
}

- (void)footerAction{
    NetWorkManager * manager = [[NetWorkManager alloc] init];
    __weak GuideViewController * weakself = self;
    int i = _contentScroller.contentOffset.x / theScreenWidth;
    _offset += 20;
    _JXoffset += 20;
    if (i == 0) {
        [manager getJXContentDataWithUrl:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/101/items?ad=2&gender=1&generation=2&limit=20&offset=%ld",(long)_JXoffset] andBlock:^(id respond) {
            NSMutableArray * packArray = [[NSMutableArray alloc] init];
            for (NSArray * arr in _firstArray) {
                [packArray addObjectsFromArray:arr];
            }
            [packArray addObjectsFromArray:respond];
            _firstArray = [[NSMutableArray alloc] initWithArray:[weakself packDataWithArray:packArray]];
            [_tableView reloadData];
            [_tableView footerEndRefreshing];
        }];
    }else{
        NavigationItem * item = _navigationArray[i - 1];
        NSMutableString * urlStr = [[NSMutableString alloc] initWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?gender=1&limit=20&offset=%ld&generation=2",item.ID,(long)_offset];
        [manager getContentDataWithUrl:urlStr andBlock:^(id respond) {
            NSMutableArray * array = [[NSMutableArray alloc] initWithArray:[_contentArray objectAtIndex:i - 1]];
            [array addObjectsFromArray:respond];
            [_contentArray setObject:array atIndexedSubscript:i - 1];
            UITableView * tableView = (UITableView *)[weakself.view viewWithTag:100 + i];
            [tableView reloadData];
            [tableView footerEndRefreshing];
        }];
    }
}

- (void)btnAction:(UIButton *)button{
    [_contentScroller setContentOffset:CGPointMake((button.tag - 200) * theScreenWidth, 0) animated:YES];
    int x = (int)button.tag - 200;
    int max = _contentScroller.contentSize.width / theScreenWidth;
    if (x < max - 3 && x > 0) {
        [_topScroller setContentOffset:CGPointMake((x - 1) * 55, 0) animated:YES];
    }
    
    [_redViewScroller setContentOffset:CGPointMake(55 * (max - x - 1), 0) animated:YES];
}

- (void)sortArray:(NSArray *)array{
    _contentArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < _navigationArray.count; i ++) {
        NavigationItem * item = _navigationArray[i];
        for (int j = 0; j < array.count; j ++) {
            NSMutableArray * dataArray = array[j];
            if ([dataArray[0] isEqual:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?generation=2&gender=1&limit=20&offset=20",item.ID]]) {
                [_contentArray addObject:dataArray];
                break;
            }
        }
    }
    
}

- (void)scrollMove{
    [_advScroller setContentOffset:CGPointMake(_advScroller.contentOffset.x + theScreenWidth, 0) animated:YES];
    if (_advScroller.contentOffset.x == 0) {
        [_advScroller setContentOffset:CGPointMake(_advArray.count * theScreenWidth, 0)];
    }else if (_advScroller.contentOffset.x == (_advArray.count + 1) * theScreenWidth)
        [_advScroller setContentOffset:CGPointMake(theScreenWidth, 0)];
    
}


- (void)tapAction:(UITapGestureRecognizer *)tap{
    AdvDetailViewController * vc = [[AdvDetailViewController alloc] init];
    if (tap.view.tag != 301 && tap.view.tag != 301 + _advArray.count + 1) {
        AdvItem * item = _advArray[tap.view.tag - 302];
        vc.Id = [item.target_id stringValue];
        vc.redirect_value = item.target_url;
        vc.advItem = item;
        [self.navigationController pushViewController:vc animated:YES];
    }
}





- (void)changeAction:(UITapGestureRecognizer *)tap{
    TopicItem * item = _topicArray[tap.view.tag - 401];
    GuideTopicViewController * vc = [[GuideTopicViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    vc.topicItem = item;
}



#pragma mark 整理精选数组的方法
- (NSArray *)packDataWithArray:(NSArray *)array{
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    NSMutableArray * packArray = [[NSMutableArray alloc] init];
    for (int i = 1; i < array.count; i ++) {
        ContentItem * item1 = array[i - 1];
        ContentItem * item2 = array[i];
        [packArray addObject:item1];
        if ([item1.created_at intValue] - [item2.created_at intValue] >= 38000 ) {
            [arr addObject:packArray];
            packArray = [[NSMutableArray alloc] init];
        }else if (array.count == i + 1){
            [packArray addObject:item2];
            [arr addObject:packArray];
            packArray = [[NSMutableArray alloc] init];
        }
    }
    return arr;
}

#pragma mark scrokller的代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == _contentScroller) {
        int x = scrollView.contentOffset.x / theScreenWidth;
        int max = scrollView.contentSize.width / theScreenWidth;
        if (x < max - 3 && x > 0) {
            [_topScroller setContentOffset:CGPointMake((x - 1) * 55, 0) animated:YES];
        }
        [_redViewScroller setContentOffset:CGPointMake(55 * (max - x - 1), 0) animated:YES];
    }else if (scrollView == _advScroller){
        if (_advScroller.contentOffset.x == 0) {
            [_advScroller setContentOffset:CGPointMake(_advArray.count * theScreenWidth, 0)];
        }else if (_advScroller.contentOffset.x == (_advArray.count + 1) * theScreenWidth)
            [_advScroller setContentOffset:CGPointMake(theScreenWidth, 0)];
    }
    
    
}

#pragma mark tableview的代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == _tableView) {
        return _firstArray.count;
    }else
        return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _tableView) {
        NSArray * array = _firstArray[section];
        return [array count];
    }else{
        if (_contentArray.count != 0) {
            NSArray * array = _contentArray[tableView.tag - 101];
            return [array count] - 1;
        }else
            return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellid = @"cell";
    
    if (tableView == _tableView) {
        GuideContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if ([_firstArray[indexPath.section][indexPath.row] class] == [ContentItem class]) {
            ContentItem * item = _firstArray[indexPath.section][indexPath.row];
            [cell.backGroundImage setImageWithURL:[NSURL URLWithString:item.cover_image_url]];
            cell.title.text = item.title;
            cell.favouriteLabel.text = item.likes_count;
        }else{
            AdvContentItem * item = _firstArray[indexPath.section][indexPath.row];
            [cell.backGroundImage setImageWithURL:[NSURL URLWithString:item.image_url]];
            cell.title.text = @"";
            cell.favouriteLabel.text = @"";
            cell.bg.alpha = 0;
        }
        CALayer * layer = cell.backGroundImage.layer;
        layer.cornerRadius = 5;
        layer.masksToBounds = YES;
        return cell;
    }else{
        ContentItem * item = [_contentArray[tableView.tag - 101] objectAtIndex:indexPath.row + 1];
        GuideContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        [cell.backGroundImage setImageWithURL:[NSURL URLWithString:item.cover_image_url]];
        CALayer * layer = cell.backGroundImage.layer;
        layer.cornerRadius = 5;
        layer.masksToBounds = YES;
        cell.title.text = item.title;
        cell.favouriteLabel.text = item.likes_count;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == _tableView) {
        return 20;
    }else
        return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == _tableView) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, 20)];
        view.backgroundColor = [UIColor whiteColor];
        ContentItem * item = _firstArray[section][0];
        long long int date1 = (long long int)[item.created_at intValue];
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:date1];
        NSDateFormatter * df = [[NSDateFormatter alloc] init];//格式化
        
        [df setDateFormat:@"   yyyy-MM-dd"];
        
        NSString * timeStr =[df stringFromDate:date];
        [view addSubview:({
            UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, 25)];
            label.text = timeStr;
            label.font = [UIFont systemFontOfSize:13];
            label.textColor = [UIColor blackColor];
            label;
        })];
        return view;
    }else
        return nil;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        if ([_firstArray[indexPath.section][indexPath.row] class] == [ContentItem class]) {
            ContentItem * item = _firstArray[indexPath.section][indexPath.row];
            DetailViewController * vc = [[DetailViewController alloc] init];
            vc.Id = item.Id;
            [self.navigationController pushViewController:vc animated:NO];
            
            
        }else{
//            AdvDetailViewController * vc = [[AdvDetailViewController alloc] init];
//            AdvContentItem * item = _firstArray[indexPath.section][indexPath.row];
//            NSMutableString * uri = [[NSMutableString alloc] initWithString:item.uri];
//            NSRange range = [uri rangeOfString:@"topic_id="];
//            vc.redirect_value = item.redirect_value;
//            vc.Id = [NSString stringWithFormat:@"%@",[uri substringFromIndex:range.location + range.length]];
//            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
        ContentItem * item = _contentArray[tableView.tag - 101][indexPath.row + 1];
        DetailViewController * vc = [[DetailViewController alloc] init];
        [self.navigationController pushViewController:vc animated:NO];
        vc.Id = item.Id;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [self.tabBarController.tabBar setHidden:NO];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
